<?php

namespace App\Services;

use App\Models\CartItem;
use Auth;

class CartService
{
    public function get()
    {
        $items = auth('api')->user()->cartItems()->with(['productSku.product'])->get();
      	$arrs = [];
        foreach ($items as $item) {
          if($item->productSku != null)
          {
          	$images = (array)$item->productSku->product->carousel_image;
            $carousel_images = array();
            foreach ($images as $img) {
                $carousel_images[] = $item->productSku->product->getImageUrl($img);
            }
            unset($item->productSku->product->description);
            $item->productSku->product->carousel_images=$carousel_images;
            $arrs[] = $item;
          }
        }
        return $arrs;
    }

    public function add($sku_id, $amount)
    {
        $user = auth('api')->user();
        // 从数据库中查询该商品是否已经在购物车中
        if ($item = $user->cartItems()->where(['product_sku_id' => $sku_id])->first()) {
            // 如果存在则直接叠加商品数量
            $item->update([
                'amount' => $item->amount + $amount,
            ]);
        } else {
            // 否则创建一个新的购物车记录
            $item = new CartItem(['amount' => $amount, 'product_sku_id' => $sku_id]);
            $item->user()->associate($user);
            $item->productSku()->associate($sku_id);
            $item->save();
        }
        return $item;
    }
    public function increase($cartItemId, $amount)
    {
        $user = auth('api')->user();
        // 从数据库中查询该商品是否已经在购物车中
        if ($item = $user->cartItems()->find($cartItemId)) {
            if ($item->amount + $amount <= $item->productSku->stock) {
                // 如果存在则直接
                $item->update([
                    'amount' => $item->amount + $amount,
                ]);
            }
        }
        return $item;
    }
    public function decrease($cartItemId, $amount)
    {
        $user = auth('api')->user();
        // 从数据库中查询该商品是否已经在购物车中
        if ($item = $user->cartItems()->find($cartItemId)) {
            if ($item->amount - $amount > 0) {
                // 如果存在则直接
                $item->update([
                    'amount' => $item->amount - $amount,
                ]);
            }
        }
        return $item;
    }
    public function remove($cartItemIds)
    {
        // 可以传单个 ID，也可以传 ID 数组
        if (!is_array($cartItemIds)) {
            $cartItemIds = [$cartItemIds];
        }
        auth('api')->user()->cartItems()->whereIn('id', $cartItemIds)->delete();
    }
}
